import { useState, useEffect, useCallback } from 'react'

interface UseCountdownReturn {
  countdown: number
  isCounting: boolean
  startCountdown: () => void
  getButtonText: () => string
}

/**
 * 60秒倒计时hook - 专用于验证码按钮
 * @returns {countdown, isCounting, startCountdown, getButtonText}
 */
export const useCountdown = (): UseCountdownReturn => {
  const [countdown, setCountdown] = useState(60)
  const [isCounting, setIsCounting] = useState(false)

  // 开始倒计时
  const startCountdown = useCallback(() => {
    setIsCounting(true)
    setCountdown(60)
  }, [])

  // 获取按钮文字
  const getButtonText = useCallback(() => {
    return isCounting ? `${countdown}秒后重试` : '获取验证码'
  }, [isCounting, countdown])

  useEffect(() => {
    let timer: number | null = null

    if (isCounting && countdown > 0) {
      timer = window.setTimeout(() => {
        setCountdown(countdown - 1)
      }, 1000)
    } else if (countdown === 0) {
      setIsCounting(false)
      setCountdown(60)
    }

    return () => {
      if (timer) {
        clearTimeout(timer)
      }
    }
  }, [isCounting, countdown])

  return {
    countdown,
    isCounting,
    startCountdown,
    getButtonText
  }
}

export default useCountdown
